package com.comac.print.component.app.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.comac.print.component.app.common.exception.PrintCommonException;
import com.itextpdf.io.util.UrlUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.FileNotFoundException;
import java.io.StringWriter;
import java.net.URL;

/**
 * @author yy
 */
@Slf4j
public class PdfHtmlUtils {

    /**
     * 根据模板生成html
     * @param data
     * @return
     * @throws FileNotFoundException
     */
    public static String getContent(Object data,String mpUrl) {
        try{
            if (data instanceof String){
                String strJson = data.toString();
                data = JSON.parseObject(strJson, Object.class);
            }
            String s = JSON.toJSONString(data);
            JSONObject jsonObject = JSON.parseObject(s, JSONObject.class);
            JSONArray aosrIconList = jsonObject.getJSONArray("aosrIconList");
            if (CollectionUtil.isNotEmpty(aosrIconList)) {
                for (Object o : aosrIconList) {
                    JSONObject o1 = (JSONObject) o;
                    Object url = o1.get("url");
                    if (ObjectUtil.isNotNull(url)) {
                        try {
                            UrlUtil.getFinalURL(new URL((String)url));
                        } catch (Exception e) {
                            throw new Exception("icon路径有误");
                        }
                    }
                }
            }
            //FreeMarker配置
            Configuration config = new Configuration(Configuration.VERSION_2_3_25);
            config.setDefaultEncoding("UTF-8");
            //注意这里是模板所在文件夹，不是文件
            //获取最后一个"/"前面的路劲
            String startMpUrl = mpUrl.substring(0,mpUrl.lastIndexOf("/"));
            RemoteTemplateLoader templateLoader = new RemoteTemplateLoader(startMpUrl);
            config.setTemplateLoader(templateLoader);
            config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            config.setLogTemplateExceptions(false);
            //获取路径中最后一个"/"后面的路径
            String tempName =mpUrl.substring(mpUrl.lastIndexOf("/"));
            Template template = config.getTemplate(tempName);
            StringWriter writer = new StringWriter();
            //模板和数据的匹配
            template.process(data, writer);
            writer.flush();
            return writer.toString();

        }catch (Exception ex){
            log.error("PdfHtmlUtils获取信息失败: {}, {}", mpUrl, data, ex);
            throw new PrintCommonException(ex.getMessage());
        }
    }
}
